<?php
namespace App\Services;

use App\Models\CashDraw;
use App\Models\CashInfo;
use App\Models\Merchant;
use App\Models\BalanceLog;
use App\Models\Order;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MerchantService
{
    /**
     * 增加用户余额
     * @param Merchant $merchant
     * @param $total
     */
    public function incrementBalance(Merchant $merchant, $total, $operator = 'system', $remark = '')
    {
        BalanceLog::create([
            'user_id'       => $merchant->user_id,
            'merchant_id'   => $merchant->id,
            'change_type'   => BalanceLog::CHANGE_TYPE_INC,
            'amount'        => $total,
            'operator'      => $operator,
            'remark'        => $remark
        ]);
        return $merchant->increment('balance', $total);
    }

    public function decementBalance(Merchant $merchant, $total, $operator = 'system', $remark = '')
    {
        BalanceLog::create([
            'user_id'       => $merchant->user_id,
            'merchant_id'   => $merchant->id,
            'change_type'   => BalanceLog::CHANGE_TYPE_DEC,
            'amount'        => $total,
            'operator'      => $operator,
            'remark'        => $remark
        ]);
        return $merchant->decrement('balance', $total);
    }

    public function frozenBalance(Merchant $merchant, $total, $operator = 'system')
    {
        $this->decementBalance($merchant, $total, $operator, '余额冻结');
        return $merchant->increment('frozen_balance', $total);
    }

    public function unfrozenBalance(Merchant $merchant, $total, $operator = 'system')
    {
        $this->incrementBalance($merchant, $total, $operator, '余额解除冻结');
        return $merchant->decrement('frozen_balance', $total);
    }

    public function cashDraw(User $user, Merchant $merchant, $amount, $operator, $remark = '')
    {
        $cashInfo = $user->cashInfo;
        DB::beginTransaction();
        try {
            // 写入资金日志
            $tradeNo = order_no();
            // 扣除用户余额
            $this->decementBalance($merchant, $amount, $operator, '提现：' . $tradeNo);
            // 创建提现请求
            CashDraw::create([
                'user_id'        => $user->id,
                'merchant_id'    => $merchant->id,
                'cash_info_id'   => $user->id,
                'cash_type'      => $cashInfo->cash_type,
                'realname'       => $cashInfo->realname,
                'account'        => $cashInfo->account,
                'amount'         => $amount,
                'remark'         => $remark,
                'trade_no'       => $tradeNo
            ]);
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            report($e);
        }
    }
}
